//
//  ViewController.m
//  JudgeDataIsImageDmeo
//
//  Created by Derkin on 1/24/14.
//  Copyright (c) 2014 Derkin. All rights reserved.
//

#import "ViewController.h"

#import "UIImage+GIF.h"
typedef enum
{
    NSPUIImageType_JPEG,
    NSPUIImageType_PNG,
    NSPUIImageType_GIF,
    NSPUIImageType_Unknown
}NSPUIImageType;
@interface ViewController ()

@end

NSString *DOCUMENTS_DIR(void) { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; }

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [self judgeDataWhetherImage:@"1"];
    
    // 测试判断gif 并最终加载显示
    [self judgeDataWhetherImage:@"2"];
    
    // 代码制作gif
    makeAnimatedGif();
    
    // 打印document
    NSLog(@"%@",DOCUMENTS_DIR());
    
    // 展示gif在iphone中的显示
    UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100, 100, 100)];
//    NSURL *fileURL = [DOCUMENTS_DIR() URLByAppendingPathComponent:@"animated.gif"];
    NSString* fileString = [DOCUMENTS_DIR() stringByAppendingPathComponent:@"animated.gif"];
    NSData* data = [NSData dataWithContentsOfFile:fileString];
    UIImage* image = [UIImage sd_animatedGIFWithData:data];
    imageView.frame = CGRectMake(0, 100, image.size.width, image.size.height);
    imageView.image = image;
    [self.view addSubview:imageView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)judgeDataWhetherImage:(NSString*)imageName

{
    NSString* path = [[NSBundle mainBundle] pathForResource:imageName ofType:nil];
    NSData* data = [NSData dataWithContentsOfFile:path];
    
    NSData* tempData = data; //请求回来的图片数据
    if (NSPUIImageTypeFromData(tempData) == NSPUIImageType_GIF)
    {
        UIImageView* imageView = [[UIImageView alloc] init];
        UIImage* image = [UIImage sd_animatedGIFWithData:tempData];
        imageView.image = image;
        imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
        [self.view addSubview:imageView];
    }
    return NO;
}


static inline NSPUIImageType NSPUIImageTypeFromData(NSData *imageData) {
    if (imageData.length > 4) {
        const unsigned char * bytes = [imageData bytes];
        
        //文件头数据
        // 可以输出一下查看
        const unsigned char byt = bytes[0];

        if (bytes[0] == 0xff &&
            bytes[1] == 0xd8 &&
            bytes[2] == 0xff)
        {
            return NSPUIImageType_JPEG;
        }
        
        if (bytes[0] == 0x89 &&
            bytes[1] == 0x50 &&
            bytes[2] == 0x4e &&
            bytes[3] == 0x47)
        {
            return NSPUIImageType_PNG;
        }
        
//        bool is = bytes[0] == 'G'; // c中比较char的方法 还有一个是 strcmp(*char ,* char) 返回类型是int
        if (bytes[0] == 'G' &&
            bytes[1] == 'I' &&
            bytes[2] == 'F') {
            return NSPUIImageType_GIF;
        }
    }
    
    return NSPUIImageType_Unknown;
}

#import <UIKit/UIKit.h>
#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>
static UIImage *frameImage(CGSize size, CGFloat radians) {
    UIGraphicsBeginImageContextWithOptions(size, YES, 1); {
        [[UIColor whiteColor] setFill];
        UIRectFill(CGRectInfinite);
        CGContextRef gc = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(gc, size.width / 2, size.height / 2);
        CGContextRotateCTM(gc, radians);
        CGContextTranslateCTM(gc, size.width / 4, 0);
        [[UIColor redColor] setFill];
        CGFloat w = size.width / 10;
        CGContextFillEllipseInRect(gc, CGRectMake(-w / 2, -w / 2, w, w));
    }
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
static void makeAnimatedGif(void) {
    static NSUInteger kFrameCount = 16;
    NSDictionary *fileProperties = @{
                                     (__bridge id)kCGImagePropertyGIFDictionary: @{
                                             (__bridge id)kCGImagePropertyGIFLoopCount: @0, // 0 means loop forever
                                             }
                                     };
    
    NSDictionary *frameProperties = @{
                                      (__bridge id)kCGImagePropertyGIFDictionary: @{
                                              (__bridge id)kCGImagePropertyGIFDelayTime: @0.02f, // a float (not double!) in seconds, rounded to centiseconds in the GIF data
                                              }
                                      };
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
    NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:@"animated.gif"];
    
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypeGIF, kFrameCount, NULL);
    CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)fileProperties);
    
    for (NSUInteger i = 0; i < kFrameCount; i++) {
        @autoreleasepool {
            UIImage *image = frameImage(CGSizeMake(300, 300), M_PI * 2 * i / kFrameCount);
            CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)frameProperties);
        }
    }
    
    if (!CGImageDestinationFinalize(destination)) {
        NSLog(@"failed to finalize image destination");
    }
    CFRelease(destination);
    
    NSLog(@"url=%@", fileURL);
}
@end
